'ui';

let userName = '17705030121'
let passWord = 'Zhong6543217'

let defalutData = {
	name: 'xxx',
	pwd: 'Zhong6543217',
	card: '聪明卡免还款',
	score: 0,
	buyCount: 1,
	appSign: 'com.cs_credit_bank',
	status: 'ok',
}

let cards = [
	'聪明卡免还款',
	'国寿广发联名卡',
	'广发智汇信用卡',
	'DIY卡免还款',
	'联通卡积分兑换免还款',
]

let isRunning = false
ui.statusBarColor('#40a5f3')
ui.layout(
	<vertical>
		<appbar bg="#40a5f3">
			<toolbar title="发现精彩辅助" />
		</appbar>
		<Switch
			gravity="right"
			id="autoService"
			text="无障碍服务"
			checked="{{auto.service != null}}"
			padding="8 8 8 8"
			textSize="15sp"
		/>
		<horizontal w="*" h="auto" marginTop="10">
			<text textSize="10sp" h="*" w="60" gravity="center" text="名字" />
			<text textSize="10sp" gravity="center" text="卡种" w="80" h="*" />
			<text textSize="10sp" h="*" w="60" gravity="center" text="积分" />
			<text textSize="10sp" h="*" w="60" gravity="center" text="数量" />
			<text textSize="10sp" h="*" w="80" gravity="center" text="密码" />
			<text
				textSize="10sp"
				h="*"
				layout_weight="1"
				gravity="center"
				text="状态"
			/>
		</horizontal>
		<list id="dataList" w="*" h="auto" textSize="10sp">
			<vertical marginBottom="10" w="*">
				<horizontal w="*" h="30" marginTop="4">
					<text
						id="name"
						textSize="10sp"
						gravity="center"
						w="60"
						h="*"
						text="{{this.name}}"
					/>
					<spinner
						id="spin"
						textSize="10sp"
						entries="聪明卡免还款|国寿广发联名卡|广发智汇信用卡|DIY卡免还款|联通卡积分兑换免还款"
						w="80"
						h="*"
						padding="0"
						margin="0"
						spinnerMode="dialog"
						text="{{this.card}}"
					/>
					<text
						id="score"
						textSize="10sp"
						w="60"
						hint="积分"
						h="*"
						gravity="center"
						text="{{this.score}}"
					/>
					<input
						id="buyCount"
						textSize="10sp"
						w="60"
						h="*"
						padding="0"
						margin="0"
						hint="数量"
						gravity="center"
						inputType="number"
						text="{{this.buyCount}}"
					/>
					<input
						id="pwd"
						textSize="10sp"
						w="80"
						h="*"
						padding="0"
						margin="0"
						hint="密码"
						gravity="center"
						text="{{this.pwd}}"
					/>
					<text
						id="status"
						textSize="10sp"
						layout_weight="1"
						h="*"
						gravity="center"
						text="{{this.status}}"
					/>
				</horizontal>
				<horizontal w="*" h="30" padding="20 0 20 0">
					<input
						id="appSign"
						textSize="10sp"
						w="0"
						margin="0"
						padding="0"
						hint="分身包名"
						gravity="center"
						layout_weight="1"
						text="{{this.appSign}}"
					/>
					<frame w="auto" margin="10 0 10 0" h="auto" layout_gravity="center">
						<img
							w="*"
							h="*"
							src="#00000000"
							borderWidth="1dp"
							scaleType="fitXY"
							borderColor="#40a5f3"
							circle="true"
						/>
						<text
							id="del"
							h="auto"
							text="删除"
							padding="10 4 10 4"
							gravity="center"
							textSize="12sp"
							textColor="#40a5f3"
						/>
					</frame>
				</horizontal>
			</vertical>
		</list>
		<horizontal margin="10" gravity="center">
			<frame w="auto" margin="10 0 10 0" h="auto" layout_gravity="center">
				<img
					w="*"
					h="*"
					src="#00000000"
					borderWidth="1dp"
					scaleType="fitXY"
					borderColor="#40a5f3"
					circle="true"
				/>
				<text
					id="add"
					h="auto"
					text="添加"
					padding="10 4 10 4"
					gravity="center"
					textSize="12sp"
					textColor="#40a5f3"
				/>
			</frame>
		</horizontal>
		<horizontal margin="10 30 10 0">
			<frame w="auto" layout_weight="1" h="auto" layout_gravity="center">
				<img
					w="*"
					h="*"
					src="#00000000"
					borderWidth="1dp"
					scaleType="fitXY"
					borderColor="#40a5f3"
					circle="true"
				/>
				<text
					id="stop"
					h="auto"
					text="停止运行"
					padding="10 4 10 4"
					gravity="center"
					textSize="12sp"
					textColor="#40a5f3"
				/>
			</frame>
			<frame
				w="auto"
				layout_weight="1"
				h="auto"
				marginLeft="20"
				layout_gravity="center"
			>
				<img
					w="*"
					h="*"
					src="#00000000"
					borderWidth="1dp"
					scaleType="fitXY"
					borderColor="#40a5f3"
					circle="true"
				/>
				<text
					id="start"
					h="auto"
					text="开始运行"
					padding="10 4 10 4"
					gravity="center"
					textSize="12sp"
					textColor="#40a5f3"
				/>
			</frame>
		</horizontal>
	</vertical>
)

var storage = storages.create('cai')
// da.push(defalutData)
let data = storage.get('cai', [])

events.on('exit', function () {
	storage.put('cai', data)
	log('结束运行')
})

ui.dataList.setDataSource(data)

let isCreated = false
setTimeout(() => {
	data.forEach((item, index) => {
		let pos = 0
		for (let i in cards) {
			let card = cards[i]
			if (card == item['card']) {
				pos = i
			}
		}
		ui.dataList.getChildAt(index).spin.setSelection(pos)
	})
	isCreated = true
}, 500)

let cur = -1
function changeCur() {
	let xCur = cur
	for (let i = 0; i <= data.length; i++) {
		if (cur == data.length - 1) {
			cur = 0
		} else {
			cur++
		}
		if (cur == xCur) {
			break
		}

		if (data[cur]['status'] == '购买成功') {
			continue
		}

		if (data[cur]['appSign'].length > 0) {
			let xx = app.launchPackage(data[cur]['appSign'])
			if (!xx) {
				toast('包名错误')
				threads.shutDownAll()
				return
			}
			waitForPackage(data[cur]['appSign'])
			// sleep(5000)

			// textMatches(/.*?/).find().forEach(item => {
			//     console.log(item.text());
			// })

			// id('ll_me').findOne(1000).click()
			// text('积分').findOne(2000).parent().click()

			// click(440, 705)
			// click(440, 705)
			return cur
		} else {
			continue
		}
	}
	if (data[cur]['appSign'] != '购买成功') {
		let xx = app.launchPackage(data[cur]['appSign'])
		if (!xx) {
			toast('包名错误')
			threads.shutDownAll()
			return
		}
		waitForPackage(data[cur]['appSign'])
		return cur
	}
	toastLog('退出脚本')
	threads.shutDownAll()
}

function updateListUi(key, value) {
	ui.run(function () {
		data[cur][key] = value
		ui.dataList.getChildAt(cur)[key].setText(value)
	})
}

ui.dataList.on('item_bind', function (itemView, itemHolder) {
	itemView.pwd.addTextChangedListener({
		afterTextChanged: function (context) {
			itemHolder.item['pwd'] = context.toString().trim()
		},
	})
	itemView.buyCount.addTextChangedListener({
		afterTextChanged: function (context) {
			context = context.toString().trim()
			if (context.length == 0) {
				itemHolder.item['buyCount'] = 0
			} else {
				itemHolder.item['buyCount'] = Number.parseInt(context)
			}
		},
	})

	itemView.appSign.addTextChangedListener({
		afterTextChanged: function (context) {
			itemHolder.item['appSign'] = context.toString().trim()
		},
	})

	itemView.spin.setOnItemSelectedListener({
		onItemSelected: function (parent, view, position, id) {
			if (isCreated) {
				itemHolder.item['card'] = cards[position]
			}
		},
		onNothingSelected: function (parent) {},
	})

	itemView.del.on('click', function () {
		data.splice(itemHolder.position, 1)
	})
})

ui.add.on('click', function () {
	data.push({
		name: 'xxx',
		pwd: '',
		card: '聪明卡免还款',
		score: 0,
		buyCount: 1,
		status: 'ok',
		appSign: '',
	})
})

ui.autoService.on('check', function (checked) {
	// 用户勾选无障碍服务的选项时，跳转到页面让用户去开启
	if (checked && auto.service == null) {
		app.startActivity({
			action: 'android.settings.ACCESSIBILITY_SETTINGS',
		})
	}
	if (!checked && auto.service != null) {
		auto.service.disableSelf()
	}
})

// 当用户回到本界面时，resume事件会被触发
ui.emitter.on('resume', function () {
	// 此时根据无障碍服务的开启情况，同步开关的状态
	ui.autoService.checked = auto.service != null
})

ui.stop.on('click', function () {
	isRunning = false
	threads.shutDownAll()
	toast('任务已经停止')
})

ui.start.on('click', function () {
	//程序开始运行之前判断无障碍服务
	if (auto.service == null) {
		toast('请先开启无障碍服务！')
		return
	}
	if (isRunning) {
		return
	}
	toast('开始运行')
	isRunning = true

	threads.start(function () {
		while (true) {
			sleep(2000)
			if (text('广发安全键盘').exists()) {
				sleep(10000)
				return
			}
			if (cur >= 0) {
				if (currentPackage() != data[cur]['appSign']) {
					app.launchPackage(data[cur]['appSign'])
				}
			}
		}
	})

	threads.start(function () {
		while (true) {
			if (id('content').className('android.widget.TextView').exists()) {
				let cons = id('content')
					.className('android.widget.TextView')
					.findOne(1000)
				updateListUi('status', cons.text())
				while (!text('我的积分').exists()) {
					back()
					sleep(300)
				}
				changeCur()
			}
			sleep(1000)
			if (text('我知道了').exists() || desc('我知道了').exists()) {
				back()
			}
			sleep(1000)
		}
	})

	threads.start(function () {
		main()
		// setInterval(() => {
		// 	changeCur()
		// },1000)
	})
})

function main() {
	changeCur()
	while (true) {
		try {
			if (id('ll_me').exists()) {
				id('ll_me').findOne(3000).click()
			}

			if (text('积分').exists()) {
				text('积分').findOne(2000).parent().click()
			}

			if (id('btn_login').exists()) {
				toast('请先登录')
				id('btn_login').findOne().click()
				// login()
				// textContains('上次登录').waitFor()
			}

			if (text('密码登录').exists()) {
				text('密码登录').findOne(1000).click()
			}

			if (text('确定').exists()) {
				text('确定').findOne(1000).click()
			}
			// 用户信息
			// userPage()

			// 积分
			scorePage()

			//购物
			shoppingPage()

			// 支付
			payPage()

			// login
			login()

			// others
			// others()
		} catch (error) {}
	}
}

function login() {
	if (text('广发安全键盘').exists()) {
		if (!text('ABC').exists()) {
			// return
			// back()
			// sleep(300)
			// back()
			while (!text('我的积分').exists()) {
				back()
				sleep(300)
			}
		}
		sleep(500)
		let pwd = data[cur]['pwd']
		console.log(pwd)
		for (let p of pwd) {
			if (new RegExp('[A-Z]').test(p)) {
				try {
					text('ABC').findOne(500).click()
				} catch (error) {
					console.log(error)
				}

				if (!text(p).exists()) {
					id('native_keyboard_capitalswitchbutton').findOne(500).click()
				}
			} else if (new RegExp('[a-z]').test(p)) {
				try {
					text('ABC').findOne(500).click()
				} catch (error) {}
				if (!text(p).exists()) {
					id('native_keyboard_capitalswitchbutton').findOne(500).click()
				}
			} else if (new RegExp('[0-9]').test(p)) {
				try {
					text('123').findOne(500).click()
				} catch (error) {}
			} else {
				throw '未知字符串'
			}
			console.log(p)
			// console.log(/[a-z]|[A-Z]/.text(p));
			text(p).findOne(500).click()
			sleep(200)
		}
		sleep(500)
		back()
		className('android.widget.Button')
			.text('登录')
			.id('login_main_btn')
			.findOne(1000)
			.click()
	}
}

function userPage() {
	if (!textContains('上次登录').exists()) {
		return
	}
	console.log('userPage')

	let name = id('login_text_view_login').findOne(1000).text()
	console.log(name)
	updateListUi('name', name)

	// className('android.support.v7.widget.RecycleView').findOne(2000).scrollForward()
	id('slide_vp').findOne(2000).child(0).child(2).click()
	sleep(1000)
}
function scorePage() {
	if (!className('android.widget.Button').desc('积分明细').exists()) {
		return
	}
	console.log('scorePage')
	let score = className('android.widget.Button')
		.desc('积分明细')
		.findOne(1000)
		.parent()
		.child(1)
		.desc()
	updateListUi('score', score)
	// updateData('score', score)
	// sleep(3000)
	// console.log(className('android.webkit.WebView').findOne());
	// let nodes = className('android.webkit.WebView').find().find(className('andriod.widget.Image'))
	// let len = nodes.length
	// console.log(len);
	// nodes[len - 1].click()
	let nodes = className('android.widget.Image').find()
	let len = nodes.length
	if (len < 2) {
		sleep(1000)
		return
	}
	nodes[len - 1].click()
	sleep(1000)
}
function shoppingPage() {
	if (!desc('道路救援').exists()) {
		return
	}
	let jd = descContains('积分').findOne(2000)
	if (!jd) {
		return
	}

	console.log('shoppingPage')
	let goods = data[cur]['card']

	let item = descContains(goods).visibleToUser().findOnce()
	if (!item) {
		if (desc('道路救援').visibleToUser().exists()) {
			swipe(
				device.width / 2,
				desc('道路救援').findOne().parent().bounds().bottom + 30,
				device.width / 2,
				0,
				200
			)
			longClick(device.width / 2, device.height / 2)
			return
		}
		swipe(
			device.width / 2,
			device.height / 2 + 200,
			device.width / 2,
			device.height / 2 ,
			200
		)
		longClick(device.width / 2, device.height / 2)
		return
	}

	let bounds = item.bounds()
	click(bounds.centerX(), bounds.centerY())

	desc('商品详情').findOne(1000)

	// let sLists = [
	// 	'聪明卡免还款',
	// 	'国寿广发联名卡',
	// 	'广发智汇信用卡',
	// 	'DIY卡免还款',
	// 	'联通卡积分兑换免还款',
	// ]

	/*let img = captureScreen()
	// img.saveTo('/storage/emulated/0/1.jpg')
	for (let i = 0; i < sLists.length; i++) {
		let cName = sLists[i]
		let item = descContains(cName).visibleToUser().findOnce()
		if (item == null) {
			continue
		}

		let bounds = item.parent().child(2).bounds()
		// log(bounds)
		console.log([bounds.left, bounds.top, bounds.width(), bounds.height()])
		console.log(item.desc() + '----' + item.parent().child(2).desc())
		let point = images.findColor(img, '#e53935', {
			region: [bounds.left, bounds.top, bounds.width(), bounds.height()],
			threads: 130,
		})

		if (point) {
			// toastLog('找到了')
			// toastLog('x = ' + point.x + ', y = ' + point.y)
			// let pBounds = item.parent().bounds()
			// click(pBounds.centerX(), pBounds.centerY())

			click(point.x, point.y)
			sleep(2000)
			return
		} else {
			// toastLog('没有找到')
		}
	}*/
	// sleep(1000)
}
function payPage() {
	if (!desc('商品详情').exists()) {
		return
	}
	let buyCount = data[cur]['buyCount']
	console.log('payPage')
	if (desc('立即兑换').exists()) {
		// exit()
		// desc('立即兑换').findOne(1000).click()
		desc('商品详情').findOne(3000).parent().findOne(desc('立即兑换')).click()
	} else if (descContains('已售罄').exists()) {
		updateListUi('status', '已售罄')
		back()
		// desc('道路救援').findOne(2000)
		sleep(500)
		changeCur()
		return
	} else {
		return
	}

	let dT = desc('兑换信息').findOne(2000)
	if (!dT) {
		// TODO do something
        toast('do something.')
        
        exit()

		while (!text('我的积分').exists()) {
			back()
			sleep(300)
		}
		changeCur()
		return
	}
	// desc('商品详情').findOne(3000).parent().findOne(desc('立即兑换')).click()
	// desc('兑换信息').findOne(3000)

	setText(Number(buyCount) - 1)
	let btn = className('android.widget.EditText')
		.findOne(1000)
		.parent()
		.find(className('android.widget.Button'))[1]
	btn.click()
	desc('兑换信息')
		.findOne(3000)
		.parent()
		.parent()
		.findOne(desc('立即兑换'))
		.click()
	descContains('我已阅读').findOne(2000)
	descMatches(/\d+,\d+积分/).findOne(3000)
	descContains('我已阅读').findOne(2000).click()
	desc('确定兑换').findOne(2000).click()
	desc('立即付款').findOne(2000).click()
	updateListUi('status', '购买成功')
	exit()
	// let errList = [
	// 	'您尚未绑定符合本商品兑换要求的卡片',
	// 	'您兑换的免还款签账额大于您账户当前欠款',
	// 	'普通积分不足',
	// 	'兑换的卡种不符',
	// 	'用户未登录',
	// 	'找不到银行卡对应信息',
	// ]
	// for (let i = 0; i < errList.length; i++) {
	// 	if (text(errList[i]).exists()) {
	// 		toastLog(errList[i])
	// 		updateListUi('status', errList[i])
	// 		// exit()
	// 		threads.shutDownAll()
	// 	}
	// }
	// threads.shutDownAll()
	// exit()
}
